import React from 'react';
import { Card, Descriptions, Button, Collapse } from 'antd';
import { RedoOutlined } from '@ant-design/icons';
import VehicleTab from './statusTabs/vehicleTab';
import DriveMotorTab from './statusTabs/driveMotorTab';
import FuelCellTab from './statusTabs/fuelCellTab';
import EngineTab from './statusTabs/engineTab';
import PositionTab from './statusTabs/positionTab';
import ExtremeDataTab from './statusTabs/extremeDataTab';
import AlarmDataTab from './statusTabs/alarmDataTab';
import VoltageDataTab from './statusTabs/voltageDataTab';
import TemperatureDataTab from './statusTabs/temperatureDataTab';
import ChargingTab from './statusTabs/chargingTab';
import { connect } from 'dva';
import { getDicByKey } from '@/support/common';
import PropTypes from 'prop-types';
import moment from 'moment';
import { CaretRightOutlined } from '@ant-design/icons';
const { Panel } = Collapse;
import { findDicByCode } from '@/support/common';
import MaskText from '@/components/MaskText';

@connect((state: any) => ({
  vehicleInfoQuery: state.vehicleInfoQuery,
  loading: state.loading.effects['vehicleInfoQuery/getDataWithRes'],
}))
export default class StatusTab extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      data: {
        protocolVersion: '',
        vin: '',
        vinFlag: '',
        messageID: '',
        serviceType: '',
        messageProtocolVersion: '',
        msgType: '',
        ngtpCreateTime: '',

        kmTotal: '',
        tripMileage: '',
        autonomie: '',
        kmMaint: '',
        nbJourMaintenance: '',
        teau: '',
        thuile: '',
        nivCarb: '',
        nivHuile: '',
        conso: '',
        // alerts: 'alertType:alertValue|1:1;22:1;210:1;0:1;215:1',
        alerts: '',
        // avgFuelConsumed: 'key配对不正确',
        lon: '',
        lat: '',
        gpsStatus: '',
        vehicleState: '',
        engineState: '',
        networkUse: '',
        rssi: '',
        tboxSatelliteNumbers: '',
        avgFuelConsumed: '',
        lightStatus: '',
        pepsStatus: '',
        socremainMileage: '',
        batteryVolt: '',
        batteryTemp: '',
        batterySoc: '',

        batteryCurrent: '',
        voltOfV1: '',
        voltOfV2: '',
        batteryQuiescentCurrent: '',
        realBattResisitance: '',
        miniBattVoltAtCranking: '',
        miniBattCurrentAtCranking: '',
        accumBattCharge: '',
        accumBattDischarge: '',
        battSOCStatus: '',
        engineVo: {},
        acAmbTemperature: '',
        acBlowerState: '',
        acCoolFanState: '',
        acRearWindWindowHeatingSignal: '',
        acCabinTemperature: '',
        wiperGear: '',
        behideWiperGear: '',
        singleTripRapidAccelerationNum: '',
        singleTripSlowDownNum: '',
        singleTripAirConditioningTime: '',
        singleTripLowSpeedDrivingTime: '',
        completeVehicleVo: {},
        driveMotorTotal: '',
        driveMotorVoList: [],
        fuelCellVo: {
          temperatureProbeList: [],
        },
        extremumVo: {},
        alarmVo: {
          alarmCodeInfo: {},
        },

        energyStorageTotal: '',
        energyStorageVoList: [],
        chargeData: {},
      },
      nowDate: '',
      current: 'vehicleTab',
      dataVisible: false,
    };
  }
  componentDidMount() {
    this.getDetail();
    this.isTabShow();
  }
  componentWillUnmount = () => {
    this.setState = (state, callback) => {
      return;
    };
  };
  static contextTypes = {
    dicData: PropTypes.any,
  };
  //判断是否是燃油车，是否渲染下方tab
  isTabShow() {
    const { dispatch } = this.props;
    const { vehicleInfoQuery } = this.props;
    dispatch({
      type: 'vehicleInfoQuery/getDataWithRes',
      payload: {
        url: '/vehicle/getvehicletype',
        vin: vehicleInfoQuery.vin,
        // vin: 'LGJETESTLIJIE0004',
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          if (response.data.driveType === 'EV' || response.data.driveType === 'PHEV') {
            this.setState({
              dataVisible: true,
            });
          }
        }
      },
    });
  }

  getDetail() {
    const { vehicleInfoQuery } = this.props;
    const { dispatch } = this.props;

    vehicleInfoQuery.vin
      ? dispatch({
          type: 'vehicleInfoQuery/getDataWithRes',
          payload: {
            url: '/vehicle/getvehiclestatus',
            vin: vehicleInfoQuery.vin,
            // vin: 'LGJETESTM18MS0001',
          },

          callback: response => {
            if (response && response.statusCode == '0' && response.data[0]) {
              this.setState({
                nowDate: moment(Date()).format('YYYY-MM-DD HH:mm:ss'),
                data: { ...this.state.data, ...response.data[0] },
                // data: response.data[0],
              });
            }
          },
        })
      : '';
  }
  tabs = [
    {
      tab: '整车数据',
      key: 'vehicleTab',
      com: () => (
        <VehicleTab
          data2={this.state.data.completeVehicleVo}
          kmTotal={this.state.data.kmTotal}
          vehicleState={this.state.data.vehicleState}
          engineVo2={this.state.data.engineVo}
        />
      ),
    },
    {
      tab: '驱动电机数据',
      key: 'driveMotorTab',
      com: () => (
        <DriveMotorTab
          driveMotorTotal={this.state.data.driveMotorTotal}
          driveMotorVoList={this.state.data.driveMotorVoList}
        />
      ),
    },
    {
      tab: '燃料电池数据',
      key: 'fuelCellTab',
      com: () => <FuelCellTab fuelCellVo2={this.state.data.fuelCellVo} />,
    },
    {
      tab: '发动机数据',
      key: 'engineTab',
      com: () => (
        <EngineTab engineVo2={this.state.data.engineVo} engineState={this.state.data.engineState} />
      ),
    },
    {
      tab: '车辆位置',
      key: 'positionTab',
      com: () => (
        <PositionTab
          lat={this.state.data.lat}
          lon={this.state.data.lon}
          gpsStatus={this.state.data.gpsStatus}
        />
      ),
    },
    {
      tab: '极值数据',
      key: 'extremeDataTab',
      com: () => <ExtremeDataTab extremumVo2={this.state.data.extremumVo} />,
    },
    {
      tab: '报警数据',
      key: 'alarmDataTab',
      com: () => <AlarmDataTab alarmVo2={this.state.data.alarmVo} />,
    },
    {
      tab: '可充电储能装置电压数据',
      key: 'voltageDataTab',
      com: () => (
        <VoltageDataTab
          energyStorageTotal={this.state.data.energyStorageTotal}
          energyStorageVoList={this.state.data.energyStorageVoList}
        />
      ),
    },
    {
      tab: '可充电储能装置温度数据',
      key: 'temperatureDataTab',
      com: () => (
        <TemperatureDataTab
          energyStorageTotal={this.state.data.energyStorageTotal}
          energyStorageVoList={this.state.data.energyStorageVoList}
        />
      ),
    },
    {
      tab: '充电信息',
      key: 'chargingTab',
      com: () => <ChargingTab chargeData2={this.state.data.chargeData} />,
    },
  ];

  onTabChange = current => {
    this.setState({ current });
  };
  //JDA报警页面跳转
  scrollToAnchor = anchorName => {
    if (anchorName) {
      // 找到锚点
      let anchorElement = document.getElementById(anchorName);
      // 如果对应id的锚点存在，就跳转到锚点
      if (anchorElement) {
        anchorElement.scrollIntoView({ block: 'start', behavior: 'smooth' });
      }
    }
  };

  render() {
    const { loading, vehicleInfoQuery } = this.props;
    const { data, nowDate } = this.state;

    // 灯光状态分割字符串
    const lightStatus = data?.lightStatus?.split(',') || [];

    //循环遍历JDA报警
    const jdaAlerts = () => {
      const a = findDicByCode(this.context.dicData, 'jdaAlerts');
      let splitDate1 = '';
      let splitDate2: any = [];
      if (data.alerts) {
        splitDate1 = data.alerts.split('|');
        splitDate2 = splitDate1[1].split(';');
      }

      const splitDate3 = a.map((item: any, index: any) => {
        let text = '否';

        splitDate2.map((k: any, index2: any) => {
          if (
            k.split(':')[0].toString() === item.dictKey.toString() &&
            k.split(':')[1].toString() === '1'
          ) {
            text = '是';
          }
        });

        return (
          <Descriptions.Item label={item.dictValue} key={index}>
            {text}
          </Descriptions.Item>
        );
      });
      return splitDate3;
      // if (data.alerts) {
      //   const splitDate1 = data.alerts.split('|');
      //   const splitDate2 = splitDate1[1].split(';');

      //   const splitDate3 = splitDate2
      //     ? splitDate2.map((item: any, index: any) => {
      //         return data2.map((key: any, index: any) => {
      //           if (key === item.split(':')[0]) {
      //             return (
      //               <Descriptions.Item
      //                 label={getDicByKey(
      //                   this.context.dicData,
      //                   'jdaAlerts',
      //                   `${item.split(':')[0]}`,
      //                 )}
      //                 key={index}
      //               >
      //                 {item.split(':')[1] === '1' ? '是' : '否'}
      //               </Descriptions.Item>
      //             );
      //           }
      //           return null;
      //         });
      //       })
      //     : '';
      //   return splitDate3;
      // }
    };
    //判断信号强度
    const jdaRssi = (rssi: any) => {
      switch (data.networkUse) {
        case '0':
          if (rssi >= -80) {
            return '非常好';
          } else if (rssi >= -90 && rssi < -80) {
            return '好';
          } else if (rssi >= -100 && rssi < -90) {
            return '一般';
          } else if (rssi < -100) {
            return '差';
          }
          break;
        case '1':
          if (rssi >= -65) {
            return '非常好';
          } else if (rssi >= -75 && rssi < -65) {
            return '好';
          } else if (rssi >= -85 && rssi < -75) {
            return '一般';
          } else if (rssi < -85) {
            return '差';
          }
          break;
        case '2':
          if (rssi >= -88) {
            return '非常好';
          } else if (rssi >= -95 && rssi < -85) {
            return '好';
          } else if (rssi >= -105 && rssi < -95) {
            return '一般';
          } else if (rssi < -105) {
            return '差';
          } else {
            return;
          }
          break;
        default:
          return '';
      }
    };
    return (
      <>
        <Card style={{ display: 'flex', justifyContent: 'flex-end' }} bordered={false}>
          <Button
            key="back"
            type="primary"
            onClick={() => {
              this.getDetail();
              this.isTabShow();
            }}
          >
            刷新
            <RedoOutlined />
          </Button>
        </Card>

        <Descriptions bordered size="small" style={{ overflow: 'hidden' }}>
          <Descriptions.Item label="协议版本号">{data.protocolVersion}</Descriptions.Item>
          <Descriptions.Item label="设备 VIN">{vehicleInfoQuery.vin}</Descriptions.Item>
          {/* <Descriptions.Item label="设备 VIN标识">{}</Descriptions.Item> */}
          <Descriptions.Item label="消息ID">{data.messageID}</Descriptions.Item>
          <Descriptions.Item label="服务类型">{data.serviceType}</Descriptions.Item>
          <Descriptions.Item label="消息类型">{data.msgType}</Descriptions.Item>
          <Descriptions.Item label="消息发送时间">{nowDate}</Descriptions.Item>
          <Descriptions.Item label="消息版本号">{data.messageProtocolVersion}</Descriptions.Item>
          {/* <Descriptions.Item label="数据长度">{}</Descriptions.Item> */}
          <Descriptions.Item label="数据采集时间">{data.ngtpCreateTime}</Descriptions.Item>
          <Descriptions.Item label=""></Descriptions.Item>
          <Descriptions.Item label=""></Descriptions.Item>
        </Descriptions>

        <Collapse
          bordered={false}
          defaultActiveKey={['1', '2']}
          expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
          style={{ backgroundColor: '#fff' }}
        >
          <Panel header="车况数据" key="1" style={{ fontSize: '16px' }}>
            <Descriptions bordered size="small" style={{ overflow: 'hidden' }}>
              <Descriptions.Item label="总里程(km)">{data.kmTotal || '--'}</Descriptions.Item>
              <Descriptions.Item label="小计里程(km)">{data.tripMileage || '--'}</Descriptions.Item>
              <Descriptions.Item label="续航里程(km)">{data.autonomie || '--'}</Descriptions.Item>
              <Descriptions.Item label="保养里程(km)">{data.kmMaint || '--'}</Descriptions.Item>
              <Descriptions.Item label="剩余保养天数">
                {data.nbJourMaintenance || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="发动机冷却水温(℃)">{data.teau || '--'}</Descriptions.Item>
              <Descriptions.Item label="机油温度(℃)">{data.thuile || '--'}</Descriptions.Item>
              <Descriptions.Item label="机油液位(%)">{data.nivCarb || '--'}</Descriptions.Item>
              <Descriptions.Item label="燃油液位(%)">{data.nivHuile || '--'}</Descriptions.Item>
              <Descriptions.Item label="总油耗(L)">{data.conso || '--'}</Descriptions.Item>
              {/* <Descriptions.Item label="单次里程油耗">{data.avgFuelConsumed}</Descriptions.Item> */}

              <Descriptions.Item label="位置信息" span={2}>
                经度：
                <MaskText type="longitude" text={data.lon} />
                <br></br>纬度：
                <MaskText type="latitude" text={data.lat} />
              </Descriptions.Item>
              <Descriptions.Item label="JDA报警">
                <a onClick={() => this.scrollToAnchor('jda')}>查看</a>
              </Descriptions.Item>
              <Descriptions.Item label="车辆状态">
                {data.vehicleState
                  ? getDicByKey(this.context.dicData, 'vehicleState', `${data.vehicleState}`)
                  : '--'}
              </Descriptions.Item>
              <Descriptions.Item label="发动机状态">
                {data.engineState
                  ? getDicByKey(this.context.dicData, 'engineState', `${data.engineState}`)
                  : '--'}
              </Descriptions.Item>
              {/* <Descriptions.Item label="混动车的发动机状态">{}</Descriptions.Item> */}
              <Descriptions.Item label="网络使用">
                {data.networkUse
                  ? getDicByKey(this.context.dicData, 'networkUse', `${data.networkUse}`)
                  : '--'}
                {/* {data.networkUse} */}
              </Descriptions.Item>
              <Descriptions.Item label="信号强度(RSSI)">
                {jdaRssi(data.rssi) || '--'}
                {/* {data.rssi} */}
              </Descriptions.Item>
              <Descriptions.Item label="T-BOX的可视卫星数">
                {data.tboxSatelliteNumbers || '--'}
              </Descriptions.Item>
              {/* <Descriptions.Item label="T-BOX备用电池状态">{}</Descriptions.Item> */}
              <Descriptions.Item label="平均油耗(L/100km)">
                {data.avgFuelConsumed ? data.avgFuelConsumed / 1000000 : '--'}
              </Descriptions.Item>
              <Descriptions.Item label="近光灯状态">
                {lightStatus[0] ? (lightStatus[0] === '0' ? '熄灭' : '点亮') : '--'}
              </Descriptions.Item>
              <Descriptions.Item label="远光灯状态">
                {lightStatus[1] ? (lightStatus[1] === '0' ? '熄灭' : '点亮') : '--'}
              </Descriptions.Item>
              <Descriptions.Item label="后雾灯状态">
                {lightStatus[2] ? (lightStatus[2] === '0' ? '熄灭' : '点亮') : '--'}
              </Descriptions.Item>
              <Descriptions.Item label="前雾灯状态">
                {lightStatus[3] ? (lightStatus[3] === '0' ? '熄灭' : '点亮') : '--'}
              </Descriptions.Item>
              <Descriptions.Item label="位置灯状态">
                {lightStatus[4] ? (lightStatus[4] === '0' ? '熄灭' : '点亮') : '--'}
              </Descriptions.Item>
              <Descriptions.Item label="左转向灯状态">
                {lightStatus[5] ? (lightStatus[5] === '0' ? '熄灭' : '点亮') : '--'}
              </Descriptions.Item>
              <Descriptions.Item label="右转向灯状态">
                {lightStatus[6] ? (lightStatus[6] === '0' ? '熄灭' : '点亮') : '--'}
              </Descriptions.Item>
              <Descriptions.Item label="点火开关">
                {data.pepsStatus
                  ? getDicByKey(this.context.dicData, 'pepsStatus', `${data.pepsStatus}`)
                  : '--'}
              </Descriptions.Item>
              <Descriptions.Item label="混动车纯电动续航里程(km)">
                {data.socremainMileage || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="蓄电池电压/ 设备供电电压(V)">
                {data.batteryVolt || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="蓄电池温度(℃)">
                {data.batteryTemp || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="蓄电池SOC(%)">{data.batterySoc || '--'}</Descriptions.Item>
              <Descriptions.Item label="蓄电池电流(A)">
                {data.batteryCurrent || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="蓄电池V1电压(V)">{data.voltOfV1 || '--'}</Descriptions.Item>
              <Descriptions.Item label="蓄电池V2电压(V)">{data.voltOfV2 || '--'}</Descriptions.Item>
              <Descriptions.Item label="蓄电池静态电流(A)">
                {data.batteryQuiescentCurrent || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="蓄电池实时内阻(mohm)">
                {data.realBattResisitance || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="前一次启动最低电压(V)">
                {data.miniBattVoltAtCranking || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="前一次启动最小电流(A)">
                {data.miniBattCurrentAtCranking || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="累计充电容量(Ah)">
                {data.accumBattCharge || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="累计放电容量(Ah)">
                {data.accumBattDischarge || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="蓄电池SOC状态(%)">
                {data.battSOCStatus || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="发动机转速(rpm)">{data.engSpd || '--'}</Descriptions.Item>
              <Descriptions.Item label="发动机冷却水温(℃)">
                {data.teau || '--'}
                {/* {data.engineVo.engCoolantTemp} */}
              </Descriptions.Item>
              <Descriptions.Item label="车速(km/h)">{data.vehSdp || '--'}</Descriptions.Item>
              <Descriptions.Item label="环境温度(℃)">
                {data.acAmbTemperature || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="鼓风机开启状态">
                {data.acBlowerState === '0' ? '开启' : data.acBlowerState === '1' ? '关闭' : '--'}
              </Descriptions.Item>
              <Descriptions.Item label="空调冷却风扇状态(%)">
                {data.acCoolFanState || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="后风窗加热信号">
                {data.acRearWindWindowHeatingSignal === '0'
                  ? '关闭'
                  : data.acRearWindWindowHeatingSignal === '1'
                  ? '开启'
                  : '--'}
              </Descriptions.Item>
              <Descriptions.Item label="车内温度(℃)">
                {data.acCabinTemperature || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="前雨刮工作模式">
                {data.wiperGear
                  ? getDicByKey(this.context.dicData, 'wiperGear', `${data.wiperGear}`)
                  : '--'}
                {/* {data.wiperGear} */}
              </Descriptions.Item>
              <Descriptions.Item label="后雨刮工作模式">
                {data.behideWiperGear
                  ? getDicByKey(this.context.dicData, 'behideWiperGear', `${data.behideWiperGear}`)
                  : '--'}
                {/* {data.behideWiperGear} */}
              </Descriptions.Item>
              <Descriptions.Item label="本次行驶急加速次数(次)">
                {data.singleTripRapidAccelerationNum || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="本次行驶急减速次数(次)">
                {data.singleTripSlowDownNum || '--'}
              </Descriptions.Item>
              <Descriptions.Item label="本次行驶开空调时长(分钟)" span={2}>
                {data.singleTripAirConditioningTime || '--'}
              </Descriptions.Item>
              <Descriptions.Item
                label="本次行驶低速行驶时长 (车速小于20km/h)"
                span={3}
                style={{ whiteSpace: 'pre-wrap' }}
              >
                {data.singleTripLowSpeedDrivingTime
                  ? `${data.singleTripLowSpeedDrivingTime} 分钟`
                  : '--'}
                {/* {data.singleTripLowSpeedDrivingTime} */}
              </Descriptions.Item>
            </Descriptions>

            <div id="jda"></div>
            <Card
              title="JDA报警"
              bordered={false}
              loading={loading}
              style={{ fontSize: '16px', fontWeight: 'normal' }}
            >
              <Descriptions bordered size="small">
                {jdaAlerts()}
              </Descriptions>
            </Card>
          </Panel>

          {this.state.dataVisible && (
            // <Panel header="32960协议数据" key="2" style={{ fontSize: '16px' }}>
            <Panel header="32960协议数据" key="2" style={{ fontSize: '16px' }}>
              <Card
                onTabChange={this.onTabChange}
                tabList={this.tabs}
                loading={loading}
                bordered={false}
              >
                {this.tabs.find(e => e.key === this.state.current)?.com()}
              </Card>
            </Panel>
          )}
        </Collapse>
      </>
    );
  }
}
